package edu.ucsd.ccdb.servlet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.http.HttpServlet;

import edu.ucsd.ccdb.MainConfiguration;
import edu.ucsd.irods.IRODSFileString;

public class ServletSendReceive extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	StringBuffer sb = new StringBuffer();
	
	/*
	 * @param query		an urlencoded query (require)
	 */
	public static List<IRODSFileString> getResponse (String query) {
		
		StringBuffer buffer = new StringBuffer();
		List<IRODSFileString> result = new LinkedList<IRODSFileString>();
		
		try {			
			URL url = new URL( query ) ;		
			Object o = url.getContent();
			
			System.out.println (o);
			
			BufferedReader reader = new BufferedReader(new InputStreamReader (url.openStream()));
			String line = reader.readLine();
			int lineNumber = 1;
			String absolutePath = line.replace(":", "");
			
			while (line != null ) {
				buffer.append(line + "\n");				
				
				if (lineNumber != 1) {
					IRODSFileString file = getLineInfo(lineNumber, line, absolutePath);
					if (file != null)
						result.add(file);
				}
				
				lineNumber ++;				
				line = reader.readLine();
			}
		}
		catch (Exception e){
			e.printStackTrace();
		}
		
		return result;
	}
	
	
	/*
	 * Template for ils on ICommand 
	 */
	
	private static IRODSFileString getLineInfo (int lineNumber, String line, String absolutePath ) {
		if ( lineNumber == 1 ) // first line is just the name space  
			return null;
		
		String[] data = line.split("[\t ]+");
		
		// if the file is directory
		if ( data.length > 2 && data[1].equals("C-" ) ) {

			IRODSFileString node = new IRODSFileString( line.substring ( line.indexOf('/') ) , getName( line.substring ( line.indexOf('/') ) ), true );

			return node;
		}
		
		// if the file is not a directory
		if (line.matches( ".*& .*$" )) {
			int start = line.indexOf('&') + 2;
			if (start > line.length() )  return null;
			
			// get the size
			IRODSFileString node = new IRODSFileString( absolutePath + "/" + line.substring(start)  , line.substring(start) , false );
			node.setLength( Long.parseLong( data[4] ) );
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd.HH:mm");
			try {
				node.setLastModifiedDate( dateFormat.parse(data[5]) );
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
			return node;
		}		
		return null; // error
	}

	private static String getName (String absolutePath ) {
		if (absolutePath.length() >= 0)
			return absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length());
		else 
			return absolutePath;
	}
	
	public static void main (String [] args ) {
		
		List<IRODSFileString> list = ServletSendReceive.getResponse(
				"http://ccdb-stage-apps.ucsd.edu:8081/irodsClientServlet/CheckDirectoryServlet?directory=" + "/CCDBProdZone/home/CCDB_DATA_USER/acquisition/project_10143/microscopy_2490/") ;
		
		// test
		if (MainConfiguration.DEBUG) {
			for (IRODSFileString element: list ) {
				System.out.println ("Element: " + element.getAbsolutePath() );
				System.out.println ("Name: " + element.getName() );
				System.out.println("Is Directory: " + element.isDirectory() );
				System.out.println ();				
			}
		}			
	}
}
